package com.zdc.learn.netty.proto;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

public class NettyServer {

    public static void main(String[] args) {
        //NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);

//        System.out.println(Runtime.getRuntime().availableProcessors());
//        System.out.println(Runtime.getRuntime().freeMemory());
//        System.out.println(Runtime.getRuntime().maxMemory());
//        System.out.println(Runtime.getRuntime().totalMemory());
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);

        NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
        try{
            //创建服务器端启动对象，配置参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    //使用NioSocketChannel 作为服务器通道实现
                    .channel(NioServerSocketChannel.class)
                    //设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG,128)
                    //设置保持连接活动状态
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    //创建一个通道初始化对象
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder",new ProtobufDecoder(ProtoTest.Mymessage.getDefaultInstance()));
                            //接收和发送消息处理器
                            pipeline.addLast(new NettyServerHandler());
                        }

                    });

            //绑定一个端口并且同步，生成一个channelFuture 对象，启动服务器、绑定端口
            ChannelFuture future = serverBootstrap.bind(6666);

            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {

                    if (future.isSuccess()){
                        System.out.println("服务启动OK。。。。。。。。。。。。。。。");
                    }else {
                        System.out.println("服务启动error。。。。。。。。。。。。。。。");
                    }
                }
            });

            //对关闭通道进行监听
            future.channel().closeFuture().sync();
        }catch (Exception e){
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}
